package cn.com.ejiakanghu.task;

import cn.com.ejiakanghu.service.WxOrderService;
import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.lock_rfid.LockRfidUtil;
import org.linlinjava.litemall.core.lock_rfid.UnLockCabinetGoodsVo;
import org.linlinjava.litemall.core.lock_rfid.UnLockGoodsVo;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.Task;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.core.util.InventoryUtil;
import org.linlinjava.litemall.db.dao.AgedmallHospitalSendSelfLocationMapper;
import org.linlinjava.litemall.db.dao.AgedmallServiceOrderMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.util.ServiceOrderConstant;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

public class OrderUnpaidTask extends Task {
    private final Log logger = LogFactory.getLog(OrderUnpaidTask.class);
    /**
     * 大订单id
     */
    private int orderId = -1;

    public OrderUnpaidTask(Integer orderId, long delayInMilliseconds){
        super("OrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderUnpaidTask(Integer orderId){
        super("OrderUnpaidTask-" + orderId, SystemConfig.getOrderUnpaid() * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---订单超时未付款---" + this.orderId);

        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);
        LitemallOrderGoodsService orderGoodsService = BeanUtil.getBean(LitemallOrderGoodsService.class);
        AgedmallHospitalSendSelfLocationMapper agedmallHospitalSendSelfLocationMapper = BeanUtil.getBean(AgedmallHospitalSendSelfLocationMapper.class);
        WxOrderService wxOrderService = BeanUtil.getBean(WxOrderService.class);
        InventoryUtil inventoryUtil = BeanUtil.getBean(InventoryUtil.class);
        LockRfidUtil lockRfidUtil = BeanUtil.getBean(LockRfidUtil.class);
        AgedmallServiceOrderMapper agedmallServiceOrderMapper = BeanUtil.getBean(AgedmallServiceOrderMapper.class);

        LitemallOrder order = orderService.findById(this.orderId);
        if(order == null){
            return;
        }
        if(!OrderUtil.isCreateStatus(order)){
            return;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
        order.setEndTime(LocalDateTime.now());
//        if (orderService.updateWithOptimisticLocker(order) == 0) {
//            throw new RuntimeException("更新数据已失效");
//        }
        orderService.update(order);

        // 更新服务订单
        AgedmallServiceOrderExample serviceOrderExample = new AgedmallServiceOrderExample();
        serviceOrderExample.createCriteria().andDeletedEqualTo(false)
                .andOrderIdEqualTo(order.getId().longValue());
        AgedmallServiceOrder serviceOrder = new AgedmallServiceOrder();
        serviceOrder.setStat(ServiceOrderConstant.STATUS_CANCEL);
        agedmallServiceOrderMapper.updateByExampleSelective(serviceOrder, serviceOrderExample);

        // 商品货品数量增加
        Integer orderId = order.getId();
        List<LitemallOrderItem> subOrderList = orderService.queryOrderItemListByBigOrderCode(order.getOrderSn());
        for (LitemallOrderItem litemallOrder : subOrderList) {
            // 更新子订单状态
            litemallOrder.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
            litemallOrder.setEndTime(LocalDateTime.now());
            orderService.updateItem(litemallOrder);

            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.getOrderGoodsListByChildOrderCode(litemallOrder.getChildOrderCode());
            for (LitemallOrderGoods orderGoods : orderGoodsList) {
                Short number = orderGoods.getNumber();
                // 还原库存
                inventoryUtil.addBatch(orderGoods.getStoreId(), orderGoods.getStockType() == 3 ? 1 : 0, orderGoods.getStockType(),
                        orderGoods.getGoodsId(), orderGoods.getProductId(), number.intValue());

                if (StringUtils.isNotEmpty(orderGoods.getRfid())) {
                    List<String> rfidList = Arrays.asList(orderGoods.getRfid().split(","));
                    // 取消rfid锁定
                    if (InventoryUtil.STOCK_SOFTCHAIN.equals(orderGoods.getStockType())) {
                        UnLockGoodsVo unLockGoodsVo = new UnLockGoodsVo();
                        unLockGoodsVo.setRfid(rfidList);
                        int type=0;
                        //        如果为到院自提
                        AgedmallHospitalSendSelfLocation selfLocation = null;
                        if(orderGoods.getHospitalSelfLocationId()!=null){
                            selfLocation = agedmallHospitalSendSelfLocationMapper.selectByPrimaryKey(orderGoods.getHospitalSelfLocationId());
                        }
                        if(ObjectUtil.isNotNull(selfLocation)&&selfLocation.getInventoryFlag()==0){
                            type=2;
                        }
                        unLockGoodsVo.setType(type);
                        lockRfidUtil.unlockGoods(unLockGoodsVo);
                    }
                    if (InventoryUtil.STOCK_CABINET.equals(orderGoods.getStockType())) {
                        UnLockCabinetGoodsVo unLockCabinetGoodsVo = new UnLockCabinetGoodsVo();
                        unLockCabinetGoodsVo.setRfid(rfidList);
                        lockRfidUtil.unlockCabinetGoods(unLockCabinetGoodsVo);
                    }
                }
            }
        }


        //返还优惠券
        wxOrderService.releaseCoupon(orderId);

        logger.info("系统结束处理延时任务---订单超时未付款---" + this.orderId);
    }
}